//
//  AddressManageViewController.m
//  wtshoppingcite
//
//  Created by TW on 14-11-14.
//  Copyright (c) 2014年 TW. All rights reserved.
//

#import "AddressManageViewController.h"
#import "DeliveryDetailViewController.h"
#import "AddressModel.h"
#import "RegisterHelper.h"

@interface AddressManageViewController ()<UITableViewDelegate,UITableViewDataSource,deliveryDetailViewDelegate>
{
    UITableView *addressManageTableView;
}
@property(strong,nonatomic)UILabel *address;
@property(strong,nonatomic)UIButton *chooseButton;

@end

@implementation AddressManageViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [RegisterHelper shareHelper].delAddrArray = [[NSMutableArray alloc]initWithCapacity:1];
    
    _isEdit = NO;
    _deleteArray = [[NSMutableArray alloc]initWithCapacity:1];
    _addressArray = [[NSMutableArray alloc]initWithCapacity:1];
    _flag = NO;
    
    //获取收货地址
    [self getAddressData];
    
    [self setTitleView:@"地址管理"];
    [self setRightButton:@"编辑" sel:@selector(editAction) viewController:self];
    
    addressManageTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, kWidth, 70*_addressArray.count)];
    addressManageTableView.dataSource = self;
    addressManageTableView.delegate = self;
   // addressManageTableView.scrollEnabled = YES;
    [self.view addSubview:addressManageTableView];
    
    
    NSInteger y;
    
    if (IS_4_INCH_SCREEN) {
        y = 450;
    }else{
        y = 360;
    }
    _cancelButton = [[UIButton alloc]initWithFrame:CGRectMake(10, kHeight-64-50, kWidth-20, 40)];
    _edit = [NSString stringWithFormat:@"删除(%ld)",_deleteArray.count];
    [_cancelButton setTitle:_edit forState:UIControlStateNormal];
    [_cancelButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_cancelButton setBackgroundImage:[UIImage imageNamed:@"register_login"] forState:UIControlStateNormal];
    [_cancelButton addTarget:self action:@selector(deleteButtonAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_cancelButton];
    
     _isFinsh = NO;
}

#pragma mark uitableView - delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

#pragma mark uitableView - dataSource
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _addressArray.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    UITableViewCell *cell =[tableView dequeueReusableCellWithIdentifier:@"shareCellIdentitfer"];
    
    if (cell == nil) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"shareCellIdentitfer"];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        
        UILabel* address = [[UILabel alloc]initWithFrame:CGRectMake(40,10,260, 60)];
        address.numberOfLines = 0;
        address.font = [UIFont systemFontOfSize:14.0f];
        address.backgroundColor = [UIColor clearColor];
        address.textColor = UIColorFromRGB(0x9fa0a0);
        address.tag = 300;
        [cell.contentView addSubview:address];
        
        UIButton* button = [[UIButton alloc]initWithFrame:CGRectMake(0,30, 20, 20)];
        button.right = _address.left - 8;
        button.tag = indexPath.row + 100;
        button.hidden = YES;
        [button addTarget:self action:@selector(selectedAddressAction:) forControlEvents:UIControlEventTouchUpInside];
        [cell.contentView addSubview:button];
        
    }
    
    for (id subView in cell.contentView.subviews) {
        if([subView isKindOfClass:[UIButton class]]){
            UIButton *button = subView;
            button.tag = indexPath.row + 100;
            break;
        }
       
    }
    
    UILabel* label = (UILabel*)[cell.contentView viewWithTag:300];
    
    AddressModel *addressModel = _addressArray[indexPath.row];
    NSString *address = [NSString stringWithFormat:@"%@  %@%@%@%@%@%@",addressModel.name,addressModel.phone,addressModel.province,addressModel.city,addressModel.area,addressModel.address,addressModel.code];
    label.text = address;
    
    UIButton* button = (UIButton*)[cell.contentView viewWithTag:indexPath.row + 100];
    [button setImage:[UIImage imageNamed:@"choose"] forState:UIControlStateNormal];

    
    if(_isEdit == YES){
        button.hidden = NO;
        button.left = 10;
    }else{
        button.hidden = YES;
    }

    return cell;
    
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (_isFinsh) {
        AddressModel *addressModel = _addressArray[indexPath.row];
        [RegisterHelper shareHelper].addressModel = addressModel;
        
        DeliveryDetailViewController *deliveryDetailVC = [[DeliveryDetailViewController alloc]init];
        deliveryDetailVC.hidesBottomBarWhenPushed = YES;
        deliveryDetailVC.addressModel = addressModel;
        deliveryDetailVC.isModify = YES;
        [self.navigationController pushViewController:deliveryDetailVC animated:YES];
        
        
    }
}

#pragma mark deliveryDetailVC --delegate
-(void)commitAddress{
    
    //获取收货地址
    [self getAddressData];
    [addressManageTableView reloadData];
}


#pragma mark editAction 勾选需删除的地址
-(void)editAction{
    
    _isEdit = YES;
    
    _isFinsh = NO;
    
    [self setRightButton:@"修改" sel:@selector(finishAction) viewController:self];
    
    
    [addressManageTableView reloadData];
}

#pragma mark editAction 修改地址
-(void)finishAction{
    
    _isFinsh = YES;
     _isEdit = NO;
    [self setRightButton:@"编辑" sel:@selector(editAction) viewController:self];
    
    [_deleteArray removeAllObjects];
    _edit = [NSString stringWithFormat:@"删除(%ld)",_deleteArray.count];
    [_cancelButton setTitle:_edit forState:UIControlStateNormal];
    [addressManageTableView reloadData];
}


#pragma mark 删除选中的
-(void)deleteButtonAction{
    
    NSInteger count = [RegisterHelper shareHelper].delAddrArray.count;
    
    NSMutableArray *deleteArray = [[NSMutableArray alloc]initWithCapacity:1];
    
    for (int i = 0; i<count; i++) {
        AddressModel *addressModel = [[RegisterHelper shareHelper].delAddrArray objectAtIndex:i];
        [deleteArray addObject:addressModel.shipId];
    }
    _edit = [NSString stringWithFormat:@"删除(%ld)",_deleteArray.count];
    [_cancelButton setTitle:_edit forState:UIControlStateNormal];
    //删除地址
    [self deleteAddressList:deleteArray];
    
    
}


#pragma mark deleteAddressList  删除收货地址
-(void)deleteAddressList:(NSArray *)deleteArray{
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    SetValueForKey(params, deleteArray, @"shipIds");
    __weak AddressManageViewController *weak_self = self;
    [NetWorkService byRequestWithAPIPrefix:kBaseAppUrl
                              andAPISuffix:kAddressDelete
                             andHttpMethod:@"POST"
                             andParameters:params
                           andRequestCache:NO
                            andUseParamDic:YES
                       andPostDataEncoding:MKNKPostDataEncodingTypeJSON
                     andRequestFinishBlock:^(BYRequest *request, BYResponse *response){
                         
                         if (response.isError) {
                             
                             DLog(@"error %@",response.errorMessage);
                         
                         }else{
                             
                             NSDictionary *responseDic = request.responseJSON;
                             DLog(@"成功数据:%@",responseDic);
                                 //删除地址之后再清除数组
                            [[RegisterHelper shareHelper].delAddrArray removeAllObjects];
                             [weak_self getAddressData];
                             
                         }
                         
                     }];
}

#pragma mark getAddressData  获取收货地址
-(void)getAddressData{
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    NSString *userId = [RegisterHelper shareHelper].userId;
    SetValueForKey(params, userId, @"userId");
    
    [NetWorkService byRequestWithAPIPrefix:kBaseAppUrl
                              andAPISuffix:kAddressList
                             andHttpMethod:@"POST"
                             andParameters:params
                           andRequestCache:NO
                            andUseParamDic:YES
                       andPostDataEncoding:MKNKPostDataEncodingTypeJSON
                     andRequestFinishBlock:^(BYRequest *request, BYResponse *response) {
                         
                         if (response.isError) {
                             DLog(@"error %@",response.errorMessage);
                         }else{
                             
                             [_addressArray removeAllObjects];
                             
                             NSDictionary *responseDic = request.responseJSON;
                             DLog(@"成功数据:%@",responseDic);
                             
                             NSArray *list = [responseDic objectForKey:@"list"];
                             DLog(@"数据列表:%@",list);
                             
                             for (NSDictionary *dic in list) {
                                 AddressModel *addressModel = [[AddressModel alloc]initWithAddressInfo:dic];
                                 [_addressArray addObject:addressModel];
                             }
                             
                             addressManageTableView.height =70*_addressArray.count;
                             addressManageTableView.alpha = 1;
                             
                            [addressManageTableView reloadData];
                         }
                     }];
}

#pragma mark 选中
-(void)selectedAddressAction:(UIButton *)btn{
    
    long index = btn.tag - 100;
    
    if(_flag == NO){
        [btn setImage:[UIImage imageNamed:@"choose_select_org.png"] forState:UIControlStateNormal];
        _flag = YES;
        
        [[RegisterHelper shareHelper].delAddrArray addObject:self.addressArray[index]];
        
    }else{
        
        [btn setImage:[UIImage imageNamed:@"choose"] forState:UIControlStateNormal];
        _flag = NO;
        [[RegisterHelper shareHelper].delAddrArray removeObject:self.addressArray[index]];
    }
    
    NSLog(@"需删除的数组下标%@",[RegisterHelper shareHelper].delAddrArray);
    _edit = [NSString stringWithFormat:@"删除(%d)",[RegisterHelper shareHelper].delAddrArray.count];
    [_cancelButton setTitle:_edit forState:UIControlStateNormal];

}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 70;

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    //获取收货地址
    [self getAddressData];
    [addressManageTableView reloadData];
    ;
}


- (void)viewWillDisappear:(BOOL)animated
{
    
    [super viewWillDisappear:animated];
    
    
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
